var express = require('express');
var router = express.Router();
const { add, getAll, getOne, del,reset,update,getComms,delPoster,delImg,getByParentId } = require("../api/comms.js")
/* GET users listing. */

//新增父类型
router.post('/add', async function (req, res, next) {
  const { _id,name, count, price, childId, isAttend, desc, image } = req.body;
  // 将新增父类型添加到类型数据库内
  const {comm,status}= await add({ _id,name, count, price, childId, isAttend, desc, image });
  // 判断父类型是否添加成功
  if (status) {
    res.send(comm);
  } else {
    status = false;
    res.send(status);
  }

});

// 获取父类型数据
// 和页面相关的操作
router.get('/getAll', async function (req, res, next) {
  const { curPage, eachPage,childId } = req.query;
  const data = await getAll({ curPage, eachPage,childId });
  res.send(data);
});

// 获取_id对应商品数据
router.get('/getOne', async function (req, res, next) {
  const { _id } = req.query;
  console.log(_id);
  const data = await getOne({ _id });
  res.send(data);
});

// 删除id对应子类型
router.delete('/del', async function (req, res, next) {
  const { _id } = req.query;
  const data = await del({ _id });
  res.send(data);
});

// 修改商品数据
router.patch('/reset', async function (req, res, next) {
  const { _id,childId,name,count,price,desc } = req.body;
  const data = await reset({ _id,childId,name,count,price,desc });
  res.send(data);
});


// 上传文件
router.patch('/:_id', async function (req, res, next) {
  const { _id } = req.params;
  const data = req.body;
  await update({ _id }, data);
  const result = await getOne(_id); //通过getOne拿到最新的数据
  console.log(result);
  res.send(result);
});

// 获取所有商品数据
router.get('/getComms', async function (req, res, next) {
  const data = await getComms();
  res.send(data);
});


// 图片删除
router.delete('/:_id/image/:url', async function (req, res, next) {
  const { _id, url } = req.params;
  await delImg({ _id, url }); //删除完成后台数据
  const data = await getOne(_id);  //更新后台数据
  res.send(data);
});

// 删除海报
router.delete('/:_id/commsPoster/:url', async function (req, res, next) {
  const { _id, url } = req.params;
  await delPoster({ _id, url }); //删除完成后台数据
  const data = await getOne(_id);  //更新后台数据
  res.send(data);
});

// 根据父类型查询对应商品
router.get('/getByParentId', async function (req, res, next) {
  const {parentId} = req.query;
  console.log(parentId);
  const data=await getByParentId({parentId}); 
  res.send(data);
});


module.exports = router;
